﻿using DocumentFormat.OpenXml.Office2010.Excel;
using DocumentFormat.OpenXml.Vml;
using Domain.Production_Modules;
using Domain.User;
using Infratructure.Interface;
using MediatR;
using MES.Server.API.Application.Command.Production_Modules.PurchaseOrder;
using MES.Server.API.Dto.Warehouse;
using ReturnValue;

namespace MES.Server.API.Application.Handler.Production_Modules.PurchaseOrder
{
    public class GetPurchaseOrderHander : IRequestHandler<GetPurchaseOrderCommand, ApiPaging<GetPurchaseOrderOutPut>>
    {
        private readonly IRepository<PurchaseOrderModel> purchaseOrderRepo;
        private readonly IRepository<VendorModel> vendorRepo;
        public GetPurchaseOrderHander(IRepository<PurchaseOrderModel> purchaseOrderRepo, IRepository<VendorModel> vendorRepo)
        {
            this.purchaseOrderRepo = purchaseOrderRepo;
            this.vendorRepo = vendorRepo;
        }
        /// <summary>
        /// 物料采购单列表
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<ApiPaging<GetPurchaseOrderOutPut>> Handle(GetPurchaseOrderCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiPaging<GetPurchaseOrderOutPut>();
            var purchaseOrder = purchaseOrderRepo.GetAll().Where(x=>x.IsDel==false);
            var vendor = vendorRepo.GetAll().Where(x => x.IsDel == false);
            var query = from p in purchaseOrder
                        join v in vendor on p.VendorId equals v.Id into pv
                        from v in pv.DefaultIfEmpty()
                        select new GetPurchaseOrderOutPut
                        {
                            Id = p.Id,  
                            PurchaseOrderCode = p.PurchaseOrderCode,
                            PurchaseOrderCount = p.PurchaseOrderCount,
                            ProductMaterialsName = p.ProductMaterialsName,
                            OverTime = p.OverTime,
                            PurchaseOrderDesc = p.PurchaseOrderDesc,
                            Status = p.Status,
                            CreaterPeople = p.CreaterPeople,
                            CreateTime = p.CreateTime,
                            VendorId = v.Id,
                            VendorName = v.VendorName,
                            ProductMaterialsId = p.ProductMaterialsId
                        };
            if(!string.IsNullOrEmpty(request.ProductMaterialsName))
            {
                query = query.Where(x => x.ProductMaterialsName.Contains(request.ProductMaterialsName));
            }
            result.TotalPage = query.OrderByDescending(x => x.CreateTime).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();
            result.Totalcount = query.Count();
            result.Code = StatusCode.Success;
            return Task.FromResult(result);
        }
    }
}
